//
//  WBStatusViewModel.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/6/5.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import Foundation

/// 单条微博的视图模型
class WBStatusViewModel: CustomStringConvertible {
    
    /// 微博模型
    var status:WBStatus
    
    /// 会员图标
    var memberIcon: UIImage?
    
    /// vip认证图标
    var vipIcon: UIImage?
    
    /// 转发文字
    var fowardStr :String?
    
    /// 评论文字
    var commentStr: String?
    
    /// 点赞文字
    var favorStr: String?

    /// 配图视图大小
    var pictureViewSize: CGSize = CGSize()
    
    /// 处理原创和转发的图片
    var picURLs: [WBStatusPicture]? {
        
        return status.retweeted_status?.pic_urls ?? status.pic_urls
    }
    
    /// 转发微博正文
    var retweetedText : String?
    
    var rowHeight: CGFloat = 0
    
    init(model: WBStatus) {
        
        self.status = model
        
        // 设置用户的等级图标
        let mbrank = model.user?.mbrank ?? 1
        
        if mbrank > 0 && mbrank < 8 {
            
            let imageName = "home_membership_level\(mbrank)"
            
            memberIcon = UIImage(named: imageName)
        }
        
        // 设置用户的认证图标
        let vertified_type = model.user?.vertified_type ?? -1
        
        switch vertified_type {
            
        case 0:
            
            vipIcon = UIImage(named: "home_avatar_vip")
            
        case 2, 3, 5:
            
            vipIcon = UIImage(named: "home_avatar_enterprise")
            
        case 220:
            
            vipIcon = UIImage(named: "home_avatar_grassroot")
            
        default:
            
            break
        }
        
        // 设置底部toolBar的数字显示
        fowardStr = countStr(count: model.reposts_count, defaultStr: "转发")
        commentStr = countStr(count: model.comments_count, defaultStr: "评论")
        favorStr = countStr(count: model.attitudes_count, defaultStr: "赞")
        
        // 设置配置图片视图的大小
        pictureViewSize = calcPictureViewSize(count: picURLs?.count)
        
        // 设置转发微博正文
        retweetedText = "@" + (status.retweeted_status?.user?.screen_name ?? "") +
 ":" + (status.retweeted_status?.text ?? "")
        
        updateRowHeight()
    }
    
    /// 返回数字的文字描述
    ///
    /// - Parameters:
    ///   - count: 数字
    ///   - defaultStr: 默认描述 转发/评论/赞
    /// - Returns: 数字的文字描述，如果不符合规则就返回默认值
    
    /**
     如果数值等于0，显示默认标题
     如果数值超过10000，显示x.xx万
     如果数值 < 10000,显示实际数字
     */
    private func countStr(count: Int, defaultStr: String) -> String  {
        
        if count == 0 {
            
            return defaultStr
            
        } else if count < 10000 {
            
            return count.description
        } else {
            
            return String(format: "%.02f万", Double(count) / 10000)
        }
    }
    
    /// 计算配图视图的大小
    ///
    /// - Parameter count: 配图数量
    /// - Returns: 配图视图的大小
    private func calcPictureViewSize(count: Int?) -> CGSize {
        
        guard let count = count else {
            
            return CGSize()
        }

        //计算高度
        let row = (count - 1) / 3
        
        var height = WBStatusPictureViewInnerMargin
        
        height += CGFloat(row) * WBStatusPictureWidth
        
        height += CGFloat(row) * WBStatusPictureViewInnerMargin

        return CGSize(width: WBStatusPictureWidth, height: height)
    }
    
    var description: String {
        
        return status.description
    }
    
    /// 更新单张图片的配图视图大小
    ///
    /// - Parameter image: 单张图片
    func updateSingleImageSize(image: UIImage) {
        
        var size = image.size
        
        // 设置图片最大高度
        let maxWidth: CGFloat = 300
        
        // 设置图片最大高度
        let minWidth: CGFloat = 40
        
        if size.width > maxWidth {
            
            size.width = maxWidth
            
            size.height = size.width * (image.size.height / image.size.width)
        }
        
        if size.width < minWidth {
            
            size.width = minWidth
            
            size.height = size.width * (image.size.height / image.size.width)
        }
        
        size.height += WBStatusPictureViewInnerMargin * 2
        
        pictureViewSize = size
        
        updateRowHeight()
    }
    
    /// 根据当前视图内容计算行高
    func updateRowHeight() {
        
        // 原创微博： 顶部分割视图(12) + 间距(12) + 头像的高度(34) + 间距(12) + 正文高度(需要计算) + 配图视图高度(需要计算) + 底部工具栏高度(35)
        // 被转发微博：顶部分割视图(12) + 间距(12) + 头像的高度(34) + 间距(12) + 正文高度(需要计算) + 间距(12) + 转发微博的文字高度(需要计算) + 配图视图高度(需要计算) + 底部工具栏高度(35)
        
        let margin: CGFloat = 12
        let iconHeight: CGFloat = 34
        let toolBarHeight: CGFloat = 35
        
        var height: CGFloat = 0
        
        let viewSize = CGSize(width: UIScreen.main.bounds.width - 2 * margin, height: CGFloat (MAXFLOAT))
        let originalFont = UIFont.systemFont(ofSize: 15)
        let retweetedFont = UIFont.systemFont(ofSize: 15)

        height = 2 * margin + iconHeight + margin
        
        //计算微博正文高度
        if let text = status.text {
            
           height += (text as NSString).boundingRect(with: viewSize,
                                             options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: originalFont], context: nil).height
        }
        
        // 判断是不是有转发微博
        if status.retweeted_status?.text != nil{
            
            height += margin
            
            if let text = retweetedText {
                
                height += (text as NSString).boundingRect(with: viewSize,
                                                                    options: [.usesLineFragmentOrigin], attributes: [NSFontAttributeName: retweetedFont], context: nil).height
            }
        }
        
        height += pictureViewSize.height
        
        height += toolBarHeight
        
        rowHeight = height
    }
    
}
